package com.zhi.controller;

import com.zhi.config.Constant;
import com.zhi.entity.Faculty;
import com.zhi.entity.Grade;
import com.zhi.entity.GradeTeacher;
import com.zhi.entity.Teacher;
import com.zhi.service.*;
import com.zhi.util.PageUtil;
import com.zhi.util.PubFun;
import com.zhi.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 院系班级信息Controller
 */
@Controller
public class GradeController {

    Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
    GradeService gradeService;
	
	@Autowired
    TeacherService teacherService;

	@Autowired
	MaxValueService maxValueService;

	@Autowired
	FacultyService facultyService;

	@Autowired
    GradeTeacherService gradeTeacherService;

    /**
     * 班级列表
     * @param model
     * @param pageUtil
     * @return
     */
    @RequestMapping("/toGrade")
    public String toGrade(Model model,PageUtil pageUtil) {
    	
    	//1、初始化分页工具
    	pageUtil = PageUtil.init(pageUtil);
    	Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize());
    	
    	//2、查询分页数据
    	Page<Grade> pageList= gradeService.getEntityListWithCodeName(pageable);
    	List<Grade> grades = pageList.getContent();
        
        //3、设置总页数
    	pageUtil.setTotalPages(pageList.getTotalPages());
    	
    	//4、返回前台数据
    	model.addAttribute("pageUtil", pageUtil);
        model.addAttribute("grades", grades);
        return "grade/list";
    }

    /**
     * 跳转增加班级列表
     * @param model
     * @return
     */
    @RequestMapping("/grade/toAdd")
    public String toAdd(Model model) {

        //1、查询所有院系
        List<Faculty> facultys = facultyService.getEntityList();

        //2、查询所有教师，可指定该班级的指导员，或任课教师
    	List<Teacher> teachers = teacherService.getEntityList();

        model.addAttribute("facultys", facultys);
    	model.addAttribute("teachers", teachers);

        return "grade/add";
    }

    /**
     * 增加院系班级
     * @param grade
     * @return
     */
    @RequestMapping("/grade/add")
    @ResponseBody
    public R add(Grade grade) {

        //1、存储班级主表信息
        //班级编号：班级标识号+年份+学院后3位+序号，例3001 2016 001 002
        //查询code对应的最大值，若无结果取0并更新1，若有结果取n并更新n+1
        String facultyId = grade.getFacultyId();
        String facultyIdEnd3 = facultyId.substring(facultyId.length()-3);
        String gradeIdBegin11 = Constant.ID_BEGIN_FACULTY_GRADE + facultyIdEnd3;
        Integer maxValue = maxValueService.getMax(gradeIdBegin11);
        if(maxValue == null){
            maxValue = 0;
        }
        maxValueService.saveCodeAndValue(gradeIdBegin11,maxValue + 1);
        //取得最大值后，补全位数要求
        String gradeIdEnd3 = PubFun.getStandardChar(maxValue + 1,3);
        //补全编号前缀
        String gradeId = gradeIdBegin11 + gradeIdEnd3;
        grade.setGradeId(gradeId);

        //2、存储班级主表并返回存储的对象，包含id
        gradeService.save(grade);

        //3、循环处理多选的教师
        List<GradeTeacher> list = new ArrayList<GradeTeacher>();

        //3.1取得传入的班级编号与多个教师的id
        String teacherIds = grade.getTeacherIds();
        //3.2用","拆分教师ids
        String[] teacherArr = teacherIds.split(",");
        //3.3遍历教师ids
        for(String teacherId:teacherArr){
            //3.4将教师加入list待存储
            GradeTeacher selectGradeTeacher = new GradeTeacher(null,gradeId,teacherId);
            list.add(selectGradeTeacher);
        }
        //3.5将list批量存入数据库
        gradeTeacherService.saveAll(list);

        return R.ok();
    }

    /**
     * 跳转编辑院系班级列表
     * @param model
     * @param gradeId
     * @return
     */
    @RequestMapping("/grade/toEdit")
    public String toEdit(Model model,String gradeId) {

        //1、获得班级子表教师信息，获得拼接的教师ids
        String teacherIds = "";
        GradeTeacher selectGradeTeacher = new GradeTeacher(null,gradeId,null);
        List<GradeTeacher> gradeTeachers = gradeTeacherService.findAll(selectGradeTeacher);
        for(GradeTeacher gt : gradeTeachers){
            teacherIds = teacherIds + "," +gt.getTeacherId();
        }

        //2、获得班级表信息
        Grade grade = gradeService.getOne(gradeId);
        grade.setTeacherIds(teacherIds);

        //3、获得所有教师信息
        List<Teacher> teachers = teacherService.getEntityList();

        //4、查询所有学院
        List<Faculty> facultys = facultyService.getEntityList();

        model.addAttribute("teachers", teachers);
        model.addAttribute("grade", grade);
        model.addAttribute("facultys", facultys);
        return "grade/edit";
    }

    /**
     * 编辑院系班级
     * @param grade
     * @return
     */
    @RequestMapping("/grade/edit")
    public String update(Grade grade) {
        //1、保存班级主表信息
        gradeService.edit(grade);

        //2.班级教师子表每次不再比对变化，直接处理逻辑：先删除，再新增
        gradeTeacherService.deleteByGradeId(grade.getGradeId());

        //3.获得前台传入的教师ids，存储请假子表
        List<GradeTeacher> list = new ArrayList<>();
        String teacherIds = grade.getTeacherIds();//获得前台传入的教师ids
        String[] teacherIdArr = teacherIds.split(",");
        for(String teacherId:teacherIdArr){
            GradeTeacher gradeTeacher = new GradeTeacher(null,grade.getGradeId(),teacherId);
            list.add(gradeTeacher);
        }
        gradeTeacherService.saveAll(list);

        return "redirect:/toGrade";
    }

    /**
     * 删除班级主、子表
     * @param gradeId
     * @return
     */
    @RequestMapping("/grade/delete")
    public String delete(String gradeId) {
        //1、删除班级主表
        gradeService.delete(gradeId);

        //2、删除班级教师子表
        gradeTeacherService.deleteByGradeId(gradeId);

        return "redirect:/toGrade";
    }


}
